package com.jzy.gulimall.member.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.common.utils.PageUtils;
import com.jzy.common.utils.Query;
import com.jzy.gulimall.member.constant.MemberConstant;
import com.jzy.gulimall.member.dao.MemberDao;
import com.jzy.gulimall.member.entity.MemberEntity;
import com.jzy.gulimall.member.entity.MemberLevelEntity;
import com.jzy.gulimall.member.exception.PhoneException;
import com.jzy.gulimall.member.exception.UsernameException;
import com.jzy.gulimall.member.service.MemberLevelService;
import com.jzy.gulimall.member.service.MemberService;
import com.jzy.gulimall.member.vo.MemberLoginVo;
import com.jzy.gulimall.member.vo.MemberRegisterVo;
import com.jzy.gulimall.member.vo.SocialUser;
import org.springframework.stereotype.Service;
import weibo4j.Users;
import weibo4j.model.User;
import weibo4j.model.WeiboException;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册
     * 保存会员信息
     */
    @Override
    public void register(MemberRegisterVo memberRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();
        //检查用户名,手机号是否唯一
        checkUsernameUnique(memberRegisterVo.getUsername());
        checkPhoneUnique(memberRegisterVo.getPhone());
        memberEntity.setUsername(memberRegisterVo.getUsername());
        memberEntity.setMobile(memberRegisterVo.getPhone());
        //默认等级
        MemberLevelEntity default_status = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", MemberConstant.MEMBER_DEFAULT_LEAVEL));
        memberEntity.setLevelId(default_status.getId());
        //密码加密
        String hashpw = BCrypt.hashpw(memberRegisterVo.getPassword(), BCrypt.gensalt());
        memberEntity.setPassword(hashpw);
        memberEntity.setCreateTime(new Date());
        memberEntity.setStatus(1);
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneException("手机号已存在");
        }
    }

    @Override
    public void checkUsernameUnique(String username) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameException("用户名已存在");
        }
    }

    /**
     * 登录
     * 查询会员信息
     */
    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        String loginName = memberLoginVo.getLoginName();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginName).or().eq("mobile", loginName));
        if (memberEntity == null) {
            return null;
        }
        String password = memberLoginVo.getPassword();
        //密码匹配
        boolean checkpw = BCrypt.checkpw(password, memberEntity.getPassword());
        if (checkpw) return memberEntity;
        return null;
    }

    /**
     * 微博登录 登录或注册
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        String uid = socialUser.getUid();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (memberEntity != null) {
            //登录
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpireIn(socialUser.getExpireIn());
            updateById(entity);

            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpireIn(socialUser.getExpireIn());
            return memberEntity;
        } else {
            //注册
            MemberEntity entity = new MemberEntity();
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpireIn(socialUser.getExpireIn());
            entity.setUid(socialUser.getUid());
            //access_token换取用户信息
            try {
                Users users = new Users(socialUser.getAccessToken());
                User user = users.showUserById(uid);
                entity.setNickname(user.getName());
                entity.setGender("m".equalsIgnoreCase(user.getGender()) ? 1 : 0);
            } catch (WeiboException e) {
                e.printStackTrace();
            }
            baseMapper.insert(entity);
            return entity;
        }
    }

}